<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\StockLog as StockLogService;
use app\common\service\Stock as StockService;
use app\mp\admin\Distributing as DistributingAction;
use app\common\service\Sku as SkuService;
use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\MaterialReturn as MaterialReturnService;
use Endroid\QrCode\QrCode;

/**
 * 仓库物料
 * @author sparkguo
 */
class StockNew extends Admin
{

    public function initialize() {
        parent::initialize();
    }

    /**
     * 物料列表
     * @author sparkguo
     */
    public function index()
    {
        $action = $this->request->param('action/s', '');
        if($action=='changeSelfSku'){
            return $this->_changeSelfSku();
        }
        if($action=='detailList'){
            return $this->detailList();
        }
        if($action=='printrOverMaterialLabel'){//打印余料标签
            return $this->_printrOverMaterialLabel();
        }
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $materialName    = $this->request->param('material_name/s');
            $materialSku    = $this->request->param('material_sku/s');
            $selfSku    = $this->request->param('self_sku/s');
            $searchData = $this->request->request();
            if ($selfSku != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('self_sku', 'like', "%{$selfSku}%")->column('id')];
            }
            if ($materialName != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('name', 'like', "%{$materialName}%")->column('id')];
            }
            if ($materialSku != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('material_sku', '=', $materialSku)->column('id')];
            }
            if(isset($searchData['stock_m_type']) && $searchData['stock_m_type']!==''){
                $where[]=['stock_m_type','eq',$searchData['stock_m_type']];
            }
            $caigou_number=$this->request->param('caigou_number/s');
            if ($caigou_number != ''){
                $where[]=['caigou_number','eq',$caigou_number];
            }
            if(isset($searchData['material_type']) && $searchData['material_type']!==''){ //1面料 2辅料 accessories
                $logic=$searchData['material_type']==1 ? ['fabric','lining'] :['accessories'];
                $where[] = ['st.material_id', 'in', db('material')->where('type', 'in', $logic)->column('id')];
            }
            if(isset($searchData['storehouse_id']) && $searchData['storehouse_id']!==''){
                $where[]=['storehouse_id','eq',$searchData['storehouse_id']];
            }
            if(isset($searchData['factory_id']) && $searchData['factory_id']!==''){
                $where[]=['factory_id','eq',$searchData['factory_id']];
            }
            if(isset($searchData['create_date_range']) && $searchData['create_date_range']!==''){
                list($startTime, $endTime) = $searchData['create_date_range'] != '' ? array_map('strtotime', explode('~', $searchData['create_date_range']))
                    : [strtotime(date("Y-m-01 00:00:00",strtotime("-3 month"))),time()];
                $where[] = ['update_time', 'between', [$startTime, $endTime+86399]];
            }


            $where[] = ['stock', '>', 0];//筛掉库存为0的数据
            $order = 'update_time desc';
            $data['data'] = db('stock st')->where($where)->field("*,sum(stock) as stock,count(id) as unit_count")
                //->join('material m', 'st.material_id=m.id', 'left')
                ->page($page)->limit($limit)->order($order)->group('st.material_id')->select();
            $materialService = new MaterialService();
            foreach ($data['data'] as $k => &$v) {
                $data['data'][$k]['mInfo'] =$minfo= $materialService->getInfoById($v['material_id']);
                $v['self_sku']=$minfo['self_sku'];
                //$v['id']=$v['material_id'];
                $map = [
                    ['type', '=', 1],
                    ['stock_id', '=', $v['id']],
                    ['left_num', '>', 0],
                ];
                $data['data'][$k]['amount'] = sprintf('%.2f',$minfo['price']*$v['stock']);
            }
            $data['count'] = db('stock st')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $factoryKV = getFactoryKV(true);
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();

        $assign = [
            'storehouseKV'=>['' => '请选择']+$storehouseKV,
            'factoryKV' => ['' => '请选择',0=>'米莫总厂'] + $factoryKV
        ];
        $assign['stock_m_type']=  $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $template = $this->request->param('template', 'stock_list');
        return $this->assign($assign)->fetch($template);
    }

    //修改米莫sku
    private function _changeSelfSku(){
        $materialid    = $this->request->param('materialid/s');
        $selfSku    = $this->request->param('self_sku/s');
        db('material')->where('id', $materialid)->update(['self_sku' => $selfSku]);
        return $this->success('保存成功', '');
    }

    //内部sku生成
    private function getSelfSkuCode(){
        $code="YL".date("ymd");        //YL220810
        $max_selfsku=db('material')->where([['self_sku','like',$code."%"]])->order("self_sku desc")->value("self_sku",'');
        $max_selfsku=$max_selfsku!='' ? intval(substr($max_selfsku,7))+1 : 1;
        $max_selfsku=$max_selfsku<10 ? "0".$max_selfsku : $max_selfsku;
        $code.=$max_selfsku;
        $data['code'] = $code;
        $data['msg'] = 'success';
        return json($data);
    }

    //物料sku合并
    public function materialMerge(){
        $where      = $data = [];
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $checkoutMids=$mids=$this->request->param('mids/s', '');
        $checkoutMids=trim($checkoutMids,',');
        $action = $this->request->param('action/s', '');
        $material_name    = $this->request->param('material_name/s');
        $materialSku    = $this->request->param('material_sku/s');
        $selfSku    = $this->request->param('self_sku/s');
        if($action=='getSelfSkuCode'){
            return $this->getSelfSkuCode();
        }
        //执行保存合并sku操作
        if ($action=='dosave') {
            $material_ids    = $this->request->param('material_ids/s');
            $selfSku    = $this->request->param('self_sku/s');
            $material_ids=trim($material_ids,',');
            //$postData = $this->request->post();
            if(empty($selfSku)){
                return $this->error('未设置统一的内部sku', '');
            }
            $where[] = ['id', 'in', explode(',',$material_ids)];
            $res = db('material')->where($where)->update(['self_sku'=>$selfSku]);
            return $this->success('处理成功', '');;
        }

        //显示批量选中要出库的物料
        $materialService = new MaterialService();
        $factoryKV = getFactoryKV(true);
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        if ($checkoutMids != '') {
            $where[] = ['id', 'in', explode(',',$checkoutMids)];
        }
        if ($material_name != '') {
            $where[] = ['name', 'like', "%{$material_name}%"];
        }
        if ($selfSku != '') {
            $where[] = ['self_sku', 'like', "%{$selfSku}%"];
        }
        if ($materialSku != '') {
            $where[] = ['material_sku', '=', $materialSku];
        }

        $order = 'id desc';
        $datalist = db('material')->where($where)
            ->page($page)->limit($limit)->order($order)->select();
        foreach ($datalist as $k => &$v) {
            $v['minfo'] = $materialService->getInfoById($v['id']);
            $v['mtype']=$this->_formatMaterialType($v['minfo']['type']);
        }
        if($action=='datalist'){
            $data['data'] = $datalist;
            $data['count'] = db('material')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'mids'=>$mids,
            'action'=>$action,
            'storehouseKV'=>['' => '请选择']+$storehouseKV,
            'storeshelfKV'=>$storeshelfKV,
            'factoryKV' => ['' => '请选择',0=>'米莫总厂'] + $factoryKV,
            'isButton' =>1
        ];
        $assign['datalist']=$datalist;
        $assign['stock_m_type']=  $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        return $this->assign($assign)->fetch();
    }

    //物料仓库-明细 ，新建批量出库， 新增余料入库单，
    public function detailList(){
        $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $factoryKV =[0 => '未分厂(总厂)'] + getFactoryKV(true);
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $materialName    = $this->request->param('material_name/s');
            $materialSku    = $this->request->param('material_sku/s');
            $selfSku    = $this->request->param('self_sku/s');
            $searchData = $this->request->request();
            $caigou_number=$this->request->param('caigou_number/s');
            if ($caigou_number != ''){
                $caigou_number=str_replace("B",'',$caigou_number);
                $where[]=['caigou_number','like','%'.$caigou_number.'%'];
            }
            if ($selfSku != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('self_sku', 'like', "%{$selfSku}%")->column('id')];
            }
            if ($materialName != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('name', 'like', "%{$materialName}%")->column('id')];
            }
            if ($materialSku != '') {
                $where[] = ['st.material_id', 'in', db('material')->where('material_sku', '=', $materialSku)->column('id')];
            }
            if(isset($searchData['stock_m_type']) && $searchData['stock_m_type']!==''){
                $where[]=['stock_m_type','eq',$searchData['stock_m_type']];
            }
            if(isset($searchData['material_type']) && $searchData['material_type']!==''){ //1面料 2辅料 accessories
                $logic=$searchData['material_type']==1 ? ['fabric','lining'] :['accessories'];
                $where[] = ['st.material_id', 'in', db('material')->where('type', 'in', $logic)->column('id')];
            }
            if(isset($searchData['storehouse_id']) && $searchData['storehouse_id']!==''){
                $where[]=['storehouse_id','eq',$searchData['storehouse_id']];
            }
            switch ($searchData['factoryShow']) {
                case 'otherFactorys':
                    $where[]=['factory_id','gt',0];
                    break;
                case 'onlyMimo':
                    $where[]=['factory_id','eq',0];
                    break;
                case '':

                default:
            }

            if(isset($searchData['factory_id']) && $searchData['factory_id']!==''){
                $where[]=['factory_id','eq',$searchData['factory_id']];
            }
            if(isset($searchData['create_date_range']) && $searchData['create_date_range']!==''){
                list($startTime, $endTime) = $searchData['create_date_range'] != '' ? array_map('strtotime', explode('~', $searchData['create_date_range']))
                    : [strtotime(date("Y-m-01 00:00:00",strtotime("-3 month"))),time()];
                $where[] = ['update_time', 'between', [$startTime, $endTime+86399]];
            }
            $where[] = ['stock', '>', 0];//筛掉库存为0的数据
            $order = 'update_time desc,material_id desc';
            $data['data'] = db('stock st')->where($where)->field("*")
                ->page($page)->limit($limit)->order($order)->select();
            $materialService = new MaterialService();
            $storehouseKV = getStorehouseKV();
            foreach ($data['data'] as $k => &$v) {
                $data['data'][$k]['mInfo'] =$minfo= $materialService->getInfoById($v['material_id']);
                $data['data'][$k]['amount'] = sprintf('%.2f',$minfo['price']*$v['stock']);
                $v['self_sku']=$minfo['self_sku'];
                $v['storehouse_name'] = arrayGet($storehouseKV, $v['storehouse_id'], '');
                $v['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
                $v['m_type_name']=$stock_m_type[$v['stock_m_type']];
                $v['caigou_number']= empty($v['caigou_number']) ? '' : "B".$v['caigou_number'];
                $data['data'][$k]['create_time_diff'] = round( (time() - $v['update_time'])/86400);
            }
            $data['count'] = db('stock st')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $factoryKV = getFactoryKV(true);
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $mimoCount=db('stock st')->where([['factory_id','eq',0],['stock', '>', 0]])->count('id');
        $otherStockCount=db('stock st')->where([['factory_id','gt',0],['stock', '>', 0]])->count('id');
        $assign = [
            'mimoCount'=>$mimoCount,
            'otherStockCount'=>$otherStockCount,
            'storehouseKV'=>['' => '请选择']+$storehouseKV,
            'factoryKV' => ['' => '请选择'] + $factoryKV];
        $assign['stock_m_type']=  $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $template = $this->request->param('template', 'detail_list');
        return $this->assign($assign)->fetch($template);
    }

    //批量出库
    public function detailCheckOuts(){
        $where      = $data = [];
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $checkoutMids=$this->request->param('mids/s', '');
        $checkoutMids=trim($checkoutMids,',');
        $stock_ids=$this->request->param('stockids/s', '');
        $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $action = $this->request->param('action/s', '');
        $batch_number=$this->request->param("batch_number/s",'');
        $action_state=$this->request->param('action_state/s', 100);//出入库执行状态  100提交出库待入库，101出库已发货待入库，
        $postData = $this->request->post();
        if($action_state==60){ //打印出库单
            if(empty($postData['out_stockid'])){
                return $this->error('未选择出库物料', '');
            }
            $out_stockids=$postData['out_stockid'];$use_order_numbers=$stock_action_ids=[];$in_factoryids=[];
            foreach ($out_stockids as $key=>$out_stockid){
                $use_order_numbers[]=$postData['client_ordernum'][$key];
                $stock_action_ids[]=$postData['stock_action'][$key];
                $in_factoryids[]=$postData['in_factory'][$key];
                if($postData['in_factory'][$key]==='') {
                    return $this->error('打印的物料未选择订单工厂', '');
                }
            }
            $url = url('index', ['action'=>'printrOverMaterialLabel','out_ids' => implode('-', $stock_action_ids),'use_order_numbers'=>implode('-',$use_order_numbers),
                'in_factoryids'=>implode('-',$in_factoryids)]);
            return $this->Json(1, '获取成功！',['url'=>$url]);
        }

        //执行出库操作
        if ($action=='dosave') {
            $postData = $this->request->post();
            if(empty($postData['out_stockid'])){
                return $this->error('未选择出库物料', '');
            }
            $out_stockids=$postData['out_stockid'];

            foreach ($out_stockids as $key=>$out_stockid){
                $outStockinfo=db('stock')->find($out_stockid);
                if($postData['in_factory'][$key]==='' && ($action_state==101 || $action_state==110)){
                    return $this->error('选择的物料未选择目标工厂', '');
                }
                if($postData['client_ordernum'][$key]!=''){
                    $client_number=$postData['client_ordernum'][$key];
                    $hasOrder=db("order")->where("client_ordernum='$client_number'")->find();
                    if(empty($hasOrder)){
                        return $this->error('使用订单号'.$client_number.'不存在，请使用存在的订单号', '');
                    }
                }
                $outStockList[]=[
                    'out_stockid'=>$out_stockid,
                    'stock_m_type'=>$outStockinfo['stock_m_type'],
                    'stock'=>$postData['out_stock'][$key],
                    'material_id'=>$postData['material_id'][$key],
                    'in_factory'=>$postData['in_factory'][$key],
                    'apply_id'=>$postData['stock_action'][$key] ?? '',
                    'check_type' =>2, //出库
                    'caigou_number'=>$outStockinfo['caigou_number'],
                    'cloth_num'=>$outStockinfo['cloth_num'],
                    'client_ordernum'=>$postData['client_ordernum'][$key],
                    'action_state'=>$action_state
                ];
                $inStockList[]=[  //'apply_id'=>,'stock'=>,'material_id'=>,'in_factory'=>,'storehouse_id','storeshelf_id'],入库数据格式
                    'out_stockid'=>$out_stockid,
                    'apply_id'=>$postData['stock_action'][$key] ?? '',
                    'stock'=>$postData['out_stock'][$key],
                    'client_ordernum'=>$postData['client_ordernum'][$key],
                    'material_id'=>$postData['material_id'][$key],
                    'in_factory'=>$postData['in_factory'][$key],
                ];
            }
            if(empty($inStockList[0]['apply_id'])){ //调拨出库过来的入库
                $writelog=$action_state==101 ? false :true; //直接发货不需要写申请出库日志
                $ret=(new StockService())->applyCheckIn($outStockList);
                foreach ($inStockList as $index=>&$inStockinfo){
                    $inStockinfo['apply_id']=$ret[$index]['actionid'];
                }
            }
            if($action_state==110){ //面料出库
                $ret=(new StockService())->doCheckout($inStockList,'采购占用出库');
            }
            if($action_state==101){ //如果是确认发货    则直接入库，奇葩的需求，原因是收货方为外厂 管不到他们   所以减少他们操作
                $ret=(new StockService())->doCheckIn($inStockList);
            }
            return $this->success('处理成功', '');;
        }

        //显示批量选中要出库的物料
        $materialService = new MaterialService();
        $factoryKV = getFactoryKV(true);
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $systemUserKV = [0 => ''] + getSystemUserKV(null);
        if ($checkoutMids != '') {
            $where[] = ['st.material_id', 'in', explode(',',$checkoutMids)];
        }
        if($stock_ids!=''){ //出库管理过来的请求
            $where[] = ['st.id', 'in', explode(',',$stock_ids)];
            $where[] = ["sa.batch_number",'=',$batch_number];
        }else{
            $where[] = ['stock', '>', 0];//筛掉库存为0的数据
        }
        $order = 'material_id desc,update_time desc';
        $datalist = db('stock st')->where($where)
            ->join('stock_action sa', 'sa.stock_id=st.id', 'left')
            ->field("st.*,st.factory_id,sa.factory_id as select_factory_id,sa.id as action_id,sa.client_ordernum,sa.use_num,sa.adminid_create")
            ->page($page)->limit($limit)->order($order)->select();
        foreach ($datalist as $k => &$v) {
            if(empty($v['select_factory_id'])){
                $v['select_factory_id']=db('order')->where('client_ordernum', $v['client_ordernum'])->value('factory_id',0 );
            }
            $v['stockall']=sprintf('%.2f',$v['stock']+$v['apply_used']);
            $v['caigou_number']= empty($v['caigou_number']) ? '' : "B".$v['caigou_number'];
            $v['minfo'] = $materialService->getInfoById($v['material_id']);
            $v['minfo']['mtype']=$this->_formatMaterialType($v['minfo']['type']);
            $v['storehouse_name'] = arrayGet($storehouseKV, $v['storehouse_id'], '');
            $v['storeshelf_name'] = arrayGet($storeshelfKV, $v['storeshelf_id'], '');
            $v['apply_user'] = arrayGet($systemUserKV, $v['adminid_create'], '');
        }

        $assign = [
            'action'=>$action,
            'stock_m_type'=>$stock_m_type,
            'storehouseKV'=>['' => '请选择']+$storehouseKV,
            'storeshelfKV'=>$storeshelfKV,
            'factoryKV' => ['' => '请选择',0=>'米莫总厂'] + $factoryKV,
            'isButton' =>1
            ];
        $assign['datalist']=$datalist;
        $template = $this->request->param('template', 'detail_checkouts');
        return $this->assign($assign)->fetch($template);
    }

    //返回材料类型
    private function _formatMaterialType($str, $defaultVal='其它', $model=2){
        if ($model==1) {
            if ($str == 'fabric') return "<span style='color:#009688'>面料</span>";
            else if ($str == 'lining') return "<span style='color:#5FB878'>里料</span>";
            else if ($str == 'accessories') return "<span style='color:#1E9FFF'>辅料</span>";
            else return $defaultVal;
        } else if ($model==2) {
            if ($str == 'fabric') return '<span class="layui-badge layui-bg-green">面</span> ';
            else if ($str == 'lining') return '<span class="layui-badge layui-bg-cyan">里</span> ';
            else if ($str == 'accessories') return '<span class="layui-badge layui-bg-blue">辅</span> ';
            else return $defaultVal;
        }
    }

    //出库管理
    public function checkoutList(){
        $action_state = $this->request->param('action_state/d', 1);

        if ($this->request->isAjax()) {
            if($action_state==1){ //辅料出库列表

                $distributingAction = new DistributingAction();
                //获取辅料分发信息列表，
                return $distributingAction->getFuliaoDistributingList();
            }else if($action_state==2){//批量出库(调拨出库）
                return $this->_checkoutBatch();
            }else if($action_state==3){ //面料出库（占用出库）
                return $this->_checkoutFabrics();
            }
            return $this->Json(1, '获取成功！');
        }

        $fuliaoNeedDistributCount=db('distributing')->where([["status", "<", 5]])->count();
        $where[] = ["sa.type", "=", 2];
        $where[] = ["sa.check_out_type", "=", 1];
        $where[] = ["action_state", "<", 110];//未收货入库的
        $batchcount = db('stock_action sa')
            ->where($where)
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->group('sa.batch_number')
            ->count();

        $fabricsCount=db('stock_action sa')
            ->where([["sa.type", "=", 2],["sa.check_out_type", "=", 2],["sa.action_state", "<", 110]])
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->group('sa.batch_number')
            ->count();
        $assign = [
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'fuliaoNeedDistributCount'=>$fuliaoNeedDistributCount,
            'fabricsCount'=>$fabricsCount,
            'batch_count'=>$batchcount
        ];
        return $this->assign($assign)->fetch();
    }

    //出库管理-批量出库
    private function _checkoutBatch(){
        $where[] = ["sa.type", "=", 2];
        $where[] = ["check_out_type", "=", 1];//批量出库
        $where[] = ["action_state", "<", 110];
        $client_ordernum=$this->request->param("client_ordernum/s",'');
        $factory_id=$this->request->param("factory_id",'');
        if ($factory_id != ''){
            $where[] = ["sa.factory_id", "=", $factory_id];
        }
        if ($client_ordernum != ''){
            $where[] = ["sa.client_ordernum", "=", $client_ordernum];
        }
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 120);

        $list = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,m.name,m.type,m.pic,max(sa.factory_id) as factory_id,sa.action_state,group_concat(sa.stock_id) as stock_ids,
                        sa.adminid_create,sa.create_time,sa.remark,sa.client_ordernum
                        ,u.username as adminid_create_username')
            ->where($where)
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->group('sa.batch_number')
            ->page($page)->limit($limit)->orderRaw('sa.id desc')
            ->select();
        $factoryKV = ['' => '请选择'] +getFactoryKV(true);//,0=>'米莫总仓'
        $checkout_state_txt=[100=>'可出库',101=>'待领料',110=>'已领料'];
        $btn_style=[100=>'orange',101=>'cyan',110=>'green'];
        foreach ($list as $key=>&$v){
            $list[$key]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
            $v['action_text']=$v['factory_id']>0 ? '待领料' : '可出库' ; //$checkout_state_txt[$v['action_state']];
            $v['btn_style']=$v['factory_id']>0 ? "blue" : 'green'; //$btn_style[$v['action_state']];
        }
        return $this->Json(1, '获取成功！', array_values($list));
    }

    //出库管理-面料出库
    private function _checkoutFabrics(){
        $where[] = ["check_out_type", "=", 2];
        $where[] = ["sa.type", "=", 2];
        $where[] = ["action_state", "<", 110];
        $client_ordernum=$this->request->param("client_ordernum/s",'');
        $factory_id=$this->request->param("factory_id",'');
        if ($factory_id != ''){
            $where[] = ["sa.factory_id", "=", $factory_id];
        }
        if ($client_ordernum != ''){
            $where[] = ["sa.client_ordernum", "=", $client_ordernum];
        }
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 120);
        $list = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,m.name,m.type,m.pic,min(sa.factory_id) as factory_id,sa.action_state,group_concat(sa.stock_id) as stock_ids,
                        sa.adminid_create,sa.create_time,sa.remark,sa.client_ordernum
                        ,u.username as adminid_create_username')
            ->where($where)
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->group('sa.batch_number')
            ->page($page)->limit($limit)->orderRaw('sa.id desc')
            ->select();
        $factoryKV = ['' => '请选择'] +getFactoryKV(true);//,0=>'米莫总仓'
        foreach ($list as $key=>&$v){
            $orderInfo = db("order")->where('client_ordernum',$v['client_ordernum'])->find();
            $v['pic'] = (new SkuService())->getPicBySku($orderInfo['sku']);
            $list[$key]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
            $list[$key]['shipment_time_text'] = date("n月j日", $orderInfo['shipment_time']);
            $v['action_text']=$v['factory_id']>0 ? '待出库' : '待出库' ; //$checkout_state_txt[$v['action_state']];
            $v['btn_style']=$v['factory_id']>0 ? "orange" : 'orange'; //$btn_style[$v['action_state']];
        }
        return $this->Json(1, '获取成功！', array_values($list));
    }

    /**
     * 配料清单
     *
     * @author KING
     * @date 2020年6月5日
     *
     */
    public function detail() {

    }

    //执行入库操作
    public function doCheckIn(){
        $postData = $this->request->post();
        $action = $this->request->param('action/s', '');
        //提交的参数 'apply_id'=>,'stock'=>,'material_id'=>,'in_factory'=>,'storehouse_id','storeshelf_id'],
        /*$action='docheckin'; 示例参数
        $postData['applyids']=[6,14];
        $postData['stock']=[10,12];
        $postData['in_factory']=[20,21,22,23,24];
        $postData['storehouse_id']=[1,2,3,5,6];
        $postData['storeshelf_id']=[3,4,2,1,5];*/
        //执行出库操作
        if ($action=='docheckin') {
            $stockServer = new StockService();
            $applyids = $postData['applyids'];
            foreach ($applyids as $key => $applyid) {
                $new_stock[] = [
                    'apply_id' => $applyid,
                    'stock' => $postData['stock'][$key],
                    'in_factory' => $postData['in_factory'][$key],
                    'storehouse_id'=>$postData['storehouse_id'][$key],
                    'storeshelf_id'=>$postData['storeshelf_id'][$key],
                ];
            }
            $stockServer->doCheckIn($new_stock);
            return $this->Json(1, 'success', ['datakey' => 'dataval']);
        }
    }


    /**
     * 操作日志
     * @author sparkguo
     * @return \think\response\Json|string
     */
    public function log()
    {
        $factoryKV = ['' => '请选择',0=>'米莫总仓'] +getFactoryKV(true);
        $systemUserKV = getSystemUserKV(null);
        $id = $this->request->param('id/d', 0);
        $material_id=$this->request->param('material_id/d', 0);
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            if(!empty($id)){
                $where[] = ['stock_id', '=', $id];
            }
            if(!empty($material_id)){
                $where[] = ['material_id', '=', $material_id];
            }
            $order = 'id desc';
            $data['data'] = db('stock_log')->where($where)->page($page)->limit($limit)->order($order)->select();
            foreach ($data['data'] as $k => &$v) {
                $data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
                $data['data'][$k]['create_admin']=arrayGet($systemUserKV, $v['create_adminid'], '');
                $v['caigou_number']= empty($v['caigou_number']) ? '' : "B".$v['caigou_number'];
            }
            $data['count'] = db('stock_log')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = ['id' => $id,'material_id'=>$material_id];
        return $this->assign($assign)->fetch();
    }

    /**
     * 物料入库 新增或编辑
     */
    public function add() {
        $factoryKV = getFactoryKV(true);
        $unitKV = getUnitKV();
        $materialService = new MaterialService();
        $orderMaterialService = new OrderMaterialService();
        $orderService = new OrderService();
        $stockLogService = new StockLogService();
        $distributingFeedService = new DistributingFeedService();

        if ($this->request->isPost()) {

            $postData = $this->request->post();
            $feedId = $this->request->param('feed_id/d', 0); // 补料单ID
            $materialSku = $this->request->param('material_sku/s');
            $clientOrdernum = $this->request->param('client_ordernum/s');
            $unit = $this->request->param('purchasing_unit/s');
            $stock = $this->request->param('stock/d', 0);
            $factoryId = $this->request->param('factory_id/d', 0);
            $unitPrice = $this->request->param('unit_price/d', 0);
            $amount = $this->request->param('amount/d', 0);
            $materialReturnId = $this->request->param('material_return_id/d', 0); // 退料进度Id

            $materialInfo = $materialService->getInfoBySku($materialSku);
            if (!$materialInfo) {
                $this->error('您输入的物料SKU不存在');
            }

            if ($clientOrdernum == '' && empty($factoryId)) {
                $this->error('工厂和订单号不能同时为空');
            }

            $orderInfo = [];
            if ($clientOrdernum != '') {
                $orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
                if (!$orderInfo) {
                    $this->error('您输入的订单号不存在');
                }
                if ($orderInfo['factory_id']) $factoryId = $orderInfo['factory_id'];
            }

            try {
                db()->startTrans();
                $stockInfo = db('stock')->where('material_id', arrayGet($materialInfo, 'id', 0))->findOrEmpty();
                if ($stockInfo) {
                    $stockId = 0;
                    $arr['stock'] = $stockInfo['stock'] + $stock;
                    $arr['unit'] = $unit;
                    $arr['update_time'] = time();
                    $res = db('stock')->where('id', $stockInfo['id'])->update($arr);
                    if ($res !== false) $stockId = $stockInfo['id'];
                } else {
                    $arr['material_id'] = $materialInfo['id'];
                    $arr['stock'] = $stock;
                    $arr['unit'] = $unit;
                    $arr['create_time'] = $arr['update_time'] = time();
                    $stockId = db('stock')->insertGetId($arr);
                }

                // 更新退料进度表状态，标记已入库
                if ($materialReturnId) {
                    $upData = [
                        'status' => 3,
                        'duty_admin_id' => ADMIN_ID,
                        'over_time' => time(),
                    ];
                    db('material_return')->where('id', $materialReturnId)->update($upData);

                    (new MaterialReturnService())->addLog($materialReturnId, 2);
                }

                if ($stockId) {
                    $stockLog = [
                        'type' => 1,
                        'stock_id' => $stockId,
                        'material_id' => $materialInfo['id'],
                        'operate_num' => $arr['stock'],
                        'left_num' => $arr['stock'],
                        'unit_price' => $unitPrice ? : 0,
                        'amount' => $amount ? : 0,
                        'feed_id' => $feedId,
                        'factory_id' => arrayGet($orderInfo, 'factory_id', 0),
                        'order_id' => arrayGet($orderInfo, 'id', 0),
                        'client_ordernum' => arrayGet($orderInfo, 'client_ordernum', 0),
                        'sku' => arrayGet($orderInfo, 'sku', 0),
                        'remark' => '新物料入库',
                        'create_time' => time(),
                        'update_time' => time(),
                    ];

                    db('stock_log')->insertGetId($stockLog);

                    if ($orderInfo) {
                        $orderId = arrayGet($orderInfo, 'id', 0);
                        // 1、补料单状态修改为完成；
                        $feedUpdata = [
                            'status' => 4,
                            'update_time' => time(),
                        ];
                        if ($feedId) {
                            db('distributing_feed')->where('id', $feedId)->update($feedUpdata);
                        } else {
                            db('distributing_feed')->where('order_id', $orderId)->where('material_id', $materialInfo['id'])->update($feedUpdata);
                        }

                        // 2、重新检测订单物料库存，自动使用库存
                        $feedRes = $distributingFeedService->useStock($materialInfo['id'], $orderId, false);

                        /**
                         * ret=-1	该订单物料已采购完成
                         * ret=-2	该订单物料已采购在途中
                         * ret=0	服务异常
                         * ret=1	已成功使用库存完成该物料的采购
                         * ret=2	已生成采购任务单，请前往补料区查看
                         * ret=3	需手动再次发起补料
                         */
                        if ($feedRes['ret'] == 0) {
                            throw new \Exception($feedRes['msg']);
                        }

                        // 检测订单的所有辅料采购状态是否都已完成
                        $orderCount = arrayGet($orderInfo, 'quantity', 0);
                        $alist = $orderMaterialService->getListByOrderId($orderId, 'accessories');
                        $allOver = true;
                        foreach ($alist as $v) {
                            $materialId = $v['material_id'];

                            $materialDosageTotal = $orderCount*$v['material_dosage'];	// 总的用量

                            // 已使用量
                            $useNum = $stockLogService->getUseNum($materialId, $orderId);
                            if ($useNum >= $materialDosageTotal) continue;
                            else {
                                $allOver = false;
                                break;
                            }
                        }
                        if ($allOver) {
                            $upData = [
                                'status' => 4,
                                'update_time' => time(),
                            ];
                            db('distributing')->where('order_id', arrayGet($materialInfo, 'id', 0))->update($upData);
                        }

                    }
                }

                $this->addOrderLog(arrayGet($orderInfo, 'client_ordernum', 0), arrayGet($orderInfo, 'client_ordernum', ''), "辅料[{$materialInfo['name']}]入库{$stock}");
                db()->commit();

                return $this->Json(1, '辅料入库成功', ['material_sku' => $materialSku, 'stock' => $stock, 'feed_id' => $feedId, 'material_return_id' => $materialReturnId]);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '辅料入库失败'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }

        }

        $assign = [
            'factoryKV' => $factoryKV,
            'unitKV' => $unitKV
        ];
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV(0);
        $assign['amountType']=1;
        $assign['storehouseKV'] = ['' => '请选择'] + $storehouseKV;
        $assign['storeshelfKV'] = $storeshelfKV;
        $assign['_t'] = $this->request->param('_t/d', 0);
        $assign['mid'] = $this->request->param('mid/d', 0);
        $assign['feedId'] = $this->request->param('feed_id/d', 0); // 补料单ID
        $assign['materialReturnId'] = $this->request->param('material_return_id/d', 0); // 退料单ID
        $assign['materialSku'] = $this->request->param('material_sku/s');
        $assign['clientOrdernum'] = $this->request->param('client_ordernum/s');
        $assign['materialInfo'] = $materialService->getInfoBySku($assign['materialSku']);;
        $assign['orderInfo'] = $orderService->getInfoByClientOrdernum($assign['clientOrdernum']);

        if ($assign['materialInfo']) {
            $unit = db('stock')->where('material_id', $assign['materialInfo']['id'])->value('unit', '');
            if ($unit) $assign['unitKV'][$unit] = $unit;
        }

        $template = $this->request->param('template', 'add');
        return $this->assign($assign)->fetch($template);
    }

    /**
     * 辅料编辑
     */
    public function edit(){
        $stock_id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $postdata=$this->request->post();
            $stockids = $this->request->param('stock_ids/a', []);
            foreach ($stockids as $key=>$stockid){
                $oldstockinfo=db('stock')->where('id', $stockid)->find();
                $arr=[];
                $arr['stock'] = $postdata["stock"][$key];
                $arr['storehouse_id'] = $postdata["storehouse_id"][$key];
                $arr['storeshelf_id'] = $postdata["storeshelf_id"][$key];
                $arr['cloth_num'] = $postdata["cloth_num"][$key];
                $arr['factory_id'] = $postdata["factory_id"][$key];
                //$arr['stock'] = $postdata["stock"][$key];
                $arr['update_time'] = time();
                $res = db('stock')->where('id', $stockid)->update($arr);
                // 新物料记录入库操作日志
                $changeval=$postdata["stock"][$key]-$postdata['old_stock'][$key];
                $changeType=$changeval > $oldstockinfo['stock'] ? 1 : 0 ; //0出库1入库
                if($oldstockinfo['stock']!=$arr['stock'] || $oldstockinfo['storehouse_id']!=$arr['storehouse_id']){
                    //|| $oldstockinfo['storehouse_id']!=$arr['storehouse_id'] || $oldstockinfo['storeshelf_id']!=$arr['storeshelf_id'] || $oldstockinfo['cloth_num']!=$arr['cloth_num']
                    $logdata=['stock_id'=>$stockid,'material_id'=>$postdata['material_id'][$key],'stock'=>$changeval,'factory_id' =>$postdata["factory_id"][$key],'feed_id'=>$stock_id,
                        // 'caigou_number'=>$applyinfo['caigou_number'],
                        'type'=>$changeType,'old_stock'=>$postdata['old_stock'][$key]];
                    $logtxt='盘点编辑';//$stock_m_type[$applyinfo['stock_m_type']]
                    (new StockService())->addStockLog($logdata,$logtxt);
                }
            }
            if($res){
                return $this->Json(1, '操作成功');
            }else{
                return $this->Json(0, '操作失败');
            }
        }
        $mid = $this->request->param('material_id/d', 0);
        $where=[];
        if ($stock_id != '') {
            $where[] = ['id', 'eq',$stock_id];
        }
        if ($mid != '') {
            $where[] = ['material_id', 'eq',$mid];
        }
        $materialService=new MaterialService();
        $factoryKV =getFactoryKV(true);
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $stockList = db('stock')->where($where)->select();
        foreach ($stockList as $k => &$v) {
            $v['caigou_number']= empty($v['caigou_number']) ? '' : "B".$v['caigou_number'];
            $v['minfo'] = $materialService->getInfoById($v['material_id']);
            $v['minfo']['mtype']=$this->_formatMaterialType($v['minfo']['type']);
            $v['storehouse_name'] = arrayGet($storehouseKV, $v['storehouse_id'], '');
            $v['storeshelf_name'] = arrayGet($storeshelfKV, $v['storeshelf_id'], '');
        }
        $assign=[
            'datalist'=>$stockList,
            'factoryKV' => ['' => '请选择',0=>'米莫总厂'] + $factoryKV
        ];
        $storeshelfMap = [];
        foreach ($storehouseKV as $k => $nkey) {
            if ($k > 0) $storeshelfMap[$k] = getStoreshelfKV($k);
        }
        $this->assign('storeshelfMap', $storeshelfMap);
        $this->assign('storehouseKV', [0 => '总厂'] + $storehouseKV);
        $this->assign('storeshelfKV', [0 => '请选择'] + $storeshelfKV);
        $assign['stock_m_type']=  $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $template = $this->request->param('template', 'edit');
        return $this->assign($assign)->fetch($template);
    }

    /**
     * 入库管理
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/21
     */
    public function stockAction()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $tab_status = $this->request->param('status/d', 1);
            $action_logic = $tab_status==1 ? "<" : "=";
            $where = $this->_where_stockAction();

            switch ($tab_status) {
                case 1:
                case 2:
                    $list = db('stock_action sa')
                        ->field("sa.id,sa.batch_number,sa.stock_m_type,sa.action_state
                        ,sa.adminid_create,sa.create_time,sa.remark
                        ,u.username as adminid_create_username
                        ")
                        ->where($where)
//                        ->join('factory ft', "sa.factory_id=ft.id", 'left')
                        ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                        ->join('material m', 'sa.material_id=m.id', 'left')
                        ->group('sa.batch_number')
                        ->page($page)->limit($limit)->orderRaw('sa.id desc')
                        ->select();
                    $count = db('stock_action sa')
                        ->where($where)
                        ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                        ->join('material m', 'sa.material_id=m.id', 'left')
                        ->group('sa.batch_number')
                        ->count();
                    $batch_numbers = [];
                    foreach ($list as $k => $v) {
                        $batch_numbers[] = $v['batch_number'];
                    }

                    $list_detail = db('stock_action sa')
                        ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id,sa.client_ordernum
                        ,sa.adminid_create,sa.create_time,sa.use_num,caigou_number
                        ,u.username as adminid_create_username
                        ,ft.name as ft_name
                        ,m.type as material_type ,m.name as material_name,m.model,m.color
                        ,m.unit
                        ')
                        ->join('factory ft', "sa.factory_id=ft.id", 'left')
                        ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                        ->join('material m', 'sa.material_id=m.id', 'left')
                        ->where("action_state $action_logic 110 ")
                        ->where([
                            ['sa.batch_number', 'in', $batch_numbers],
                            ['sa.action_state', '<>', 999],
                        ])
                        ->orderRaw('sa.id desc')
                        ->select();
                    foreach ($list as $k => $v) {
                        $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                        $list[$k]['detail'] = [];
                        $list[$k]['client_ordernum'] = [];
                        foreach ($list_detail as $k2 => $v2) {
                            if ($v['batch_number'] == $v2['batch_number']) {
                                switch ($v['stock_m_type']) {
                                    case 1:
                                        $list[$k]['client_ordernum'][] = 'B' . $v2['client_ordernum'];
                                        break;
                                    case 0:
                                        $list[$k]['client_ordernum'][] = $v2['client_ordernum'];
                                        break;
                                }
                                $list[$k]['detail'][] = $v2;
                            }
                        }
                        $list[$k]['client_ordernum'] = implode(',', $list[$k]['client_ordernum']);
                    }
                    break;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'status' => $tab_status,
            ];
            return json($result);
        }
        $factoryKV = getFactoryKV(true);
        $this->assign('status', 1);
        $this->assign('factoryKV', [0 => '全部'] + $factoryKV);
        $stock_m_type = [];
        foreach (config('mimo.stock_m_type') as $k => $v) {
            $stock_m_type[$k + 1] = $v;
        }
        $this->assign('stock_m_type_super', [0 => '全部'] + $stock_m_type);
        return $this->fetch();
    }

    private function _where_stockAction()
    {
        $where = [];
        $where[] = ['sa.type', '=', 1];
        $tab_status = $this->request->param('status/d', 1);
        switch ($tab_status) {
            case 1:
                $where[] = ['sa.action_state', '<', 110];
                break;
            case 2:
                $where[] = ['sa.action_state', '=', 110];
                break;
        }
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $factorId = $this->request->param('factory_id/d', 0);
        $createDateRange = $this->request->param('create_date_range/s', '');
        $create_user = $this->request->param('adminid_create_name/s', '');
        $supplier = $this->request->param('supplier/s', '');
        $stock_m_type = $this->request->param('stock_m_type/d', 0);
        if ($create_user != '') {
            $where[] = ['sa.adminid_create', 'in', db('system_user')->where('nick', 'like', "%{$create_user}%")->column('id')];
        }
        if ($clientOrdernum != '') {
            $where[] = ['sa.client_ordernum', '=', $clientOrdernum];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['sa.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($factorId) {
            $where[] = ['sa.factory_id', '=', $factorId];
        }
        if ($supplier != '') {
            $where[] = ['m.supplier', 'like', $supplier];
        }
        if ($stock_m_type > 0) {
            $where[] = ['sa.stock_m_type', '=', $stock_m_type - 1];
        }
        return $where;
    }

    /**
     * 入库管理-入库执行的列表
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/22
     */
    public function stockActionDetail()
    {
        $batch_number = $this->request->param('batch_number/d', 0);
        if ($this->request->isAjax()) {
            $where = [];
            $where[] = ['sa.action_state', '<', 110];
            $where[] = ['sa.batch_number', '=', $batch_number];
            $list = db('stock_action sa')
                ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                        ,sa.adminid_create,sa.create_time,sa.use_num,sa.cloth_num
                        ,u.username as adminid_create_username
                        ,ft.name as ft_name
                        ,m.type as material_type ,m.name as material_name,m.model,m.color
                        ,m.unit
                        ')
                ->join('factory ft', "sa.factory_id=ft.id", 'left')
                ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                ->join('material m', 'sa.material_id=m.id', 'left')
                ->where($where)
                ->orderRaw('sa.id desc')
                ->select();
            $count = db('stock_action sa')
                ->join('factory ft', "sa.factory_id=ft.id", 'left')
                ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                ->join('material m', 'sa.material_id=m.id', 'left')
                ->where($where)
                ->count();
            $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
            foreach ($list as $k => $v) {
                $list[$k]['stock_m_type_txt'] = $stock_m_type[$v['stock_m_type']];
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
            ];
            return json($result);
        }
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $storeshelfMap = [];
        foreach ($storehouseKV as $k => $v) {
            if ($k > 0) $storeshelfMap[$k] = getStoreshelfKV($k);
        }
        $this->assign('batch_number', $batch_number);
        $this->assign('stock_m_type', config('mimo.stock_m_type'));
        $this->assign('storehouseKV', ['' => '请选择'] + $storehouseKV);
        $this->assign('storeshelfKV', ['' => '请选择'] + $storeshelfKV);
        $this->assign('storeshelfMap', $storeshelfMap);
        return $this->fetch();
    }

    //打印余料贴标
    private function _printrOverMaterialLabel(){
        $overMaterialId=$this->request->param('id/d', 0);
        $batch_number = $this->request->param('batch_number/d', '');
        $out_ids=$this->request->param('out_ids/s', '');
        $out_tofactoryids=$this->request->param('in_factoryids/s', '');
        $where = [];
        if(!empty($overMaterialId)){
            $where[] = ['sa.id', '=', $overMaterialId];
        }
        if(!empty($out_ids)){
            $where[] = ['sa.id', 'in', explode('-',$out_ids)];
        }
        if(!empty($batch_number)) {
            $where[] = ['sa.batch_number', '=', $batch_number];
        }
        $out_data_factoryids=[]; //存出库物料选择对应的订单工厂数据
        $out_ids_arr=explode('-',$out_ids);
        foreach (explode('-',$out_tofactoryids) as $k => $val) {
            $out_data_factoryids[$out_ids_arr[$k]]=$val;
        }
        $factoryKV = getFactoryKV(true);
        $list = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                    ,sa.adminid_create,sa.create_time,sa.use_num,sa.cloth_num
                    ,u.username as adminid_create_username
                    ,m.type as material_type ,m.name as material_name,m.model,m.color,m.material_sku,sa.client_ordernum,sa.caigou_number
                    ,m.unit
                    ')
            //->join('factory ft', "sa.factory_id=ft.id", 'left')
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->where($where)
            ->orderRaw('sa.id desc')
            ->select();
        $count = db('stock_action sa')
            ->join('factory ft', "sa.factory_id=ft.id", 'left')
            ->join('system_user u', 'sa.adminid_create=u.id', 'left')
            ->join('material m', 'sa.material_id=m.id', 'left')
            ->where($where)
            ->count();
        $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
        $bgtext=['常','备','余'];
        foreach ($list as $k => &$v) {
            $msg = "A{$v['id']}-{$v['cloth_num']}";
            $qrCode = new QrCode($msg);
            $v['qrcode'] = $qrCode->writeDataUri();
            $v['ft_name']=isset($out_data_factoryids[$v['id']]) ? $factoryKV[$out_data_factoryids[$v['id']]] : $factoryKV[$v['factory_id']] ;
            $list[$k]['stock_m_type_txt'] = $stock_m_type[$v['stock_m_type']];
            $v['bgtext']=$bgtext[$v['stock_m_type']];
        }
        $assign=[
            'out_ids'=>$out_ids,
            'clothNums'=>$list,
            'use_order_numbers'=>explode('-',$this->request->param('use_order_numbers/s', '')),
            'materialType' => config('mimo.material_type'),
        ];
        $template = $this->request->param('template', 'make_overmaterial_tag');
        return $this->assign($assign)->fetch($template);
    }

    /**
     * 入库管理-查看明细
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/22
     */
    public function stockActionDetailSelect()
    {
        $batch_number = $this->request->param('batch_number/d', 0);
        if ($this->request->isAjax()) {
            $where = [];
            $where[] = ['sa.action_state', '=', 110];
            $where[] = ['sa.batch_number', '=', $batch_number];
            $list = db('stock_action sa')
                ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                        ,sa.adminid_create,sa.create_time,sa.use_num,sa.cloth_num
                        ,sa.storehouse_id,sa.storeshelf_id
                        ,u.username as adminid_create_username
                        ,ft.name as ft_name
                        ,m.type as material_type ,m.name as material_name,m.model,m.color
                        ,m.unit
                        ')
                ->join('factory ft', "sa.factory_id=ft.id", 'left')
                ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                ->join('material m', 'sa.material_id=m.id', 'left')
                ->where($where)
                ->orderRaw('sa.id desc')
                ->select();
            $count = db('stock_action sa')
                ->join('factory ft', "sa.factory_id=ft.id", 'left')
                ->join('system_user u', 'sa.adminid_create=u.id', 'left')
                ->join('material m', 'sa.material_id=m.id', 'left')
                ->where($where)
                ->count();
            $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
            $storehouseKV = getStorehouseKV();
            $storeshelfKV = getStoreshelfKV();
            foreach ($list as $k => $v) {
                $list[$k]['stock_m_type_txt'] = $stock_m_type[$v['stock_m_type']];
                $list[$k]['storehouse_id_txt'] = $v['storeshelf_id'] > 0 ? $storehouseKV[$v['storehouse_id']] : '';
                $list[$k]['storeshelf_id_txt'] = $v['storeshelf_id'] > 0 ? $storeshelfKV[$v['storeshelf_id']] : '';
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
            ];
            return json($result);
        }
        $this->assign('batch_number', $batch_number);
        return $this->fetch();
    }

    /**
     * 入库管理-入库执行的列表--删除操作
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/22
     */
    public function stockActionDelete()
    {
        $id = $this->request->param('id/d');
        db('stock_action')->where([
            ['id', '=', $id],
        ])->update([
            'action_state' => 999,
        ]);
        return $this->success('删除成功', '');
    }

    /**
     * 入库管理-入库执行的列表--执行入库
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/23
     */
    public function stockActionCheckIn()
    {
        $param = [
            'batch_number' => $this->request->param('batch_number/d', 0),
            'storehouse_id' => $this->request->param('storehouse_id/d', 0),
            'storeshelf_id' => $this->request->param('storeshelf_id/d', 0),
            'action_ids'=>trim($this->request->param('checkin_action_ids/s', ''),',')
        ];
        $action=$this->request->param('action/s', '');
        if ($action == 'changeCheckInNum') { //编辑入库数
            $id=$this->request->param('id/d', 0);
            $value=$this->request->param('value/s', 0);
            db('stock_action')->where([
                ['id', '=', $id],
            ])->update([
                'use_num' => $value,
            ]);
            return json(['code' => 1, 'msg' => '编辑成功', 'data' => [],]);
        }

        if ($param['batch_number'] <= 0) {
            return json(['code' => 0, 'msg' => '参数有误', 'data' => [],]);
        }
        $checkinActionIds=explode(',',$param['action_ids']);
        if (count($checkinActionIds)<1) {
            return json(['code' => 0, 'msg' => '未选择要入库的数据', 'data' => [],]);
        }
        $where = [];
        $where[] = ['sa.action_state', '<', 200];
        $where[] = ['sa.id', 'in', $checkinActionIds];
        $list = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                        ,sa.adminid_create,sa.create_time,sa.use_num
                        ')
            ->where($where)
            ->orderRaw('sa.id desc')
            ->select();
        $stockServer = new StockService();
        $new_stock = [];
        foreach ($list as $key => $v) {
            $new_stock[] = [
                'apply_id' => $v['id'],
                'stock' => $v['use_num'],
                'in_factory' => $v['factory_id'],
                'storehouse_id' => $param['storehouse_id'],
                'storeshelf_id' => $param['storeshelf_id'],
            ];
        }
        $stockServer->doCheckIn($new_stock);
        return json(['code' => 1, 'msg' => '入库执行成功', 'data' => [],]);
    }

    /**
     * 入库管理--返回重置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/23
     */
    public function stockActionDoCheckInCallBack()
    {
        $ids = $this->request->param('id');
        if (count($ids) <= 0) {
            return json(['code' => 0, 'msg' => '参数有误', 'data' => [],]);
        }
        $where = [];
        $where[] = ['sa.id', 'in', $ids];
        $where[] = ['sa.action_state', '=', 110];
        $list_temp = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                        ,sa.adminid_create,sa.create_time,sa.use_num
                        ')
            ->where($where)
            ->orderRaw('sa.id desc')
            ->select();
        $batch_numbers = [];
        foreach ($list_temp as $k => $v) {
            $batch_numbers[] = $v['batch_number'];
        }
        $list = db('stock_action sa')
            ->field('sa.id,sa.batch_number,sa.stock_m_type,sa.factory_id
                        ,sa.adminid_create,sa.create_time,sa.use_num
                        ')
            ->where([
                ['sa.batch_number', 'in', $batch_numbers],
                ['sa.action_state', '=', 110],
            ])
            ->orderRaw('sa.id desc')
            ->select();

        $stockServer = new StockService();
        $new_stock = [];
        foreach ($list as $key => $v) {
            $new_stock[] = [
                'apply_id' => $v['id'],
            ];
        }
        $res = $stockServer->doCheckInCallBack($new_stock);
        return json($res);
    }

    /**
     * 验布缩水明细的入库提交
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/23
     */
    public function applyCheckInClothShrink()
    {
        $ids = $this->request->param('id');
        if (count($ids) <= 0) {
            return json(['code' => 0, 'msg' => '参数有误', 'data' => [],]);
        }
        $list = db('checkcloth_shrink cs')
            ->field('cs.id,cs.order_id,cs.client_ordernum,cs.stock_m_type,cs.order_material_id
            ,cs.stock_action_id,cs.material_id,cs.length,cs.cloth_num
            ,o.factory_id
            ')
            ->join('order o', 'cs.order_id=o.id', 'left')
            ->join('stock_action sa', 'cs.stock_action_id=sa.id', 'left')
            ->where([
                ['cs.id', 'in', $ids],
            ])
            ->whereRaw(" ( cs.stock_action_id =0 OR (sa.action_state=999) )")
            ->select();
        if (count($list) <= 0) {
            return json(['code' => 0, 'msg' => '已申请入库', 'data' => [],]);
        }
        $changeStockList = [];
        foreach ($list as $k => $v) {
            switch ($v['stock_m_type']) {
                case 1:
                    $changeStockList[] = [
                        'this_id' => $v['id'],
                        'stock' => $v['length'],
                        'material_id' => $v['material_id'],
                        'in_factory' => 0,
                        'cloth_num'=>$v['cloth_num'],
                        'stock_m_type' => $v['stock_m_type'],
                        'caigou_number' => $v['order_material_id'],
                        'order_id' => 0,
                    ];
                    break;
                case 0:
                    $changeStockList[] = [
                        'this_id' => $v['id'],
                        'stock' => $v['length'],
                        'material_id' => $v['material_id'],
                        'in_factory' => $v['factory_id'],
                        'cloth_num'=>$v['cloth_num'],
                        'stock_m_type' => $v['stock_m_type'],
                        'client_ordernum' => $v['client_ordernum'],
                        'order_id' => $v['order_id'],
                    ];
                    break;
            }
        }
        $stockServer = new StockService();
        $changeStockList = $stockServer->applyCheckIn($changeStockList);
        foreach ($changeStockList as $k => $v) {
            db('checkcloth_shrink cs')
                ->where([
                    ['cs.id', '=', $v['this_id']],
                ])->update([
                    'stock_action_id' => $v['actionid'],
                ]);
        }
        return json(['code' => 1, 'msg' => '成功', 'data' => [],]);
    }

    /**
     * 物料进度--入库
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/24
     */
    public function addPurchasing()
    {
        $mid = $this->request->param('mid/d');
        $info = db('order_material om')
            ->field('om.mid,om.order_id,om.client_ordernum,om.material_id,om.stock_m_type
            ,om.tiaoshu
            ,m.material_sku,m.type,m.unit
            ,o.factory_id,o.sku
            ')
            ->join('material m', 'om.material_id=m.id', 'left')
            ->join('order o', 'om.order_id=o.id', 'left')
            ->where([
                ['mid', '=', $mid],
            ])
            ->find();
        if ($this->request->isAjax()) {
            $stock_m_type=trim($this->request->param('stock_m_type'));
            $param = [
                'factory_id' => $this->request->param('factory_id/d', 0),
                'unit' => $this->request->param('unit/s', ''),
                'use_num' => $this->request->param('use_num/f', 0),
                'cloth_num' => trim($this->request->param('cloth_num/s', '')),
                'storehouse_id' => $this->request->param('storehouse_id/d', 0),
                'storeshelf_id' => $this->request->param('storeshelf_id/d', 0),
                'remark' => trim($this->request->param('remark/s', '')),
            ];
            if ($param['use_num'] <= 0 || $param['cloth_num'] == '' || $param['storehouse_id'] <= 0) { //|| $param['remark'] == '' $param['factory_id'] <= 0
                return json(['code' => 0, 'msg' => '数量,物料id,货仓必填', 'data' => [],]);
            }
            //1,申请入库
            $changeStockList = [];
            switch ($stock_m_type) {
                case 1: //备料
                    $changeStockList[] = [
                        'stock' => $param['use_num'],
                        'material_id' => $info['material_id'],
                        'in_factory' => $param['factory_id'],
                        'stock_m_type' => $stock_m_type,
                        'caigou_number' =>$info['mid'],
                        'order_id' => 0,
                        'sku' => '',
                        'cloth_num' => $param['cloth_num'],
                        'storehouse_id' => $param['storehouse_id'],
                        'storeshelf_id' => $param['storeshelf_id'],
                        'unit' => $param['unit'],
                        'remark' => $param['remark'],
                    ];
                    break;
                case 0: //常规料
                case 2: //余料
                    $changeStockList[] = [
                        'stock' => $param['use_num'],
                        'material_id' => $info['material_id'],
                        'in_factory' => $param['factory_id'],
                        'stock_m_type' => $stock_m_type,
                        'client_ordernum' => $info['client_ordernum'],
                        'order_id' => $info['order_id'],
                        'sku' => $info['sku'],
                        'cloth_num' => $param['cloth_num'],
                        'storehouse_id' => $param['storehouse_id'],
                        'storeshelf_id' => $param['storeshelf_id'],
                        'unit' => $param['unit'],
                        'remark' => $param['remark'],
                    ];
                    break;
            }
            $stockServer = new StockService();
            $changeStockList = $stockServer->applyCheckIn($changeStockList);
            $changeStockList = $changeStockList[0];
            //2,执行入库
            $new_stock = [];
            $new_stock[] = [
                'apply_id' => $changeStockList['actionid'],
                'stock' => $param['use_num'],
                'in_factory' => $param['factory_id'],
                'storehouse_id' => $param['storehouse_id'],
                'storeshelf_id' => $param['storeshelf_id'],
            ];
            $stockServer->doCheckIn($new_stock);
            return json(['code' => 1, 'msg' => '入库成功,即将关闭当前窗口', 'data' => [],]);
        }
        $info['stock_m_type'] == 0 ? $info['res_id'] = $info['client_ordernum'] : $info['res_id'] = 'B' . $info['mid'];
        $factoryKV = getFactoryKV(true);
        $unitKV = getUnitKV();
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $storeshelfMap = [];
        foreach ($storehouseKV as $k => $v) {
            if ($k > 0) $storeshelfMap[$k] = getStoreshelfKV($k);
        }
        $this->assign('info', $info);
        $this->assign('factoryKV', ['0' => '请选择'] + $factoryKV);
        $this->assign('storehouseKV', ['' => '请选择'] + $storehouseKV);
        $this->assign('storeshelfKV', ['' => '请选择'] + $storeshelfKV);
        $this->assign('storeshelfMap', $storeshelfMap);
        $this->assign('unitKV', $unitKV);
        return $this->fetch();
    }

    /**
     * 物料管理--入库
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/24
     */
    public function addMaterialCheckIn()
    {
        $material_sku = trim($this->request->param('material_sku/s'));
        $stock_m_type=trim($this->request->param('stock_m_type'));
        if ($this->request->isAjax()) {
            $param = [
                'material_sku' => trim($this->request->param('material_sku/s')),
                'res_id' => trim($this->request->param('res_id/s')),
                'factory_id' => $this->request->param('factory_id/d', 0),
                'unit' => $this->request->param('unit/s', ''),
                'use_num' => $this->request->param('use_num', 0),
                'cloth_num' => trim($this->request->param('cloth_num/s', '')),
                'storehouse_id' => $this->request->param('storehouse_id/d', 0),
                'storeshelf_id' => $this->request->param('storeshelf_id/d', 0),
                'remark' => trim($this->request->param('remark/s', '')),
            ];
            $postdata=$this->request->post();
            if ($param['use_num'] <= 0 || $param['cloth_num'] == '' || $param['storehouse_id'] <= 0) { //|| $param['remark'] == '' $param['factory_id'] <= 0
                return json(['code' => 0, 'msg' => '数量,物料id,货仓必填', 'data' => [],]);
            }

            //1,申请入库
            $changeStockList = [];
            switch ($stock_m_type) {
                case 1:
                    $changeStockList[] = [
                        'stock' => $param['use_num'],
                        'material_id' => $postdata['materialid'],
                        'in_factory' => $param['factory_id'],
                        'stock_m_type' => $postdata['stock_m_type'],
                        'caigou_number' => $postdata['res_id'],
                        'order_id' => 0,
                        'sku' => '',
                        'cloth_num' => $param['cloth_num'],
                        'storehouse_id' => $param['storehouse_id'],
                        'storeshelf_id' => $param['storeshelf_id'],
                        'unit' => $param['unit'],
                        'remark' => $param['remark'],
                    ];
                    break;
                case 0:
                    $changeStockList[] = [
                        'stock' => $param['use_num'],
                        'material_id' => $postdata['materialid'],
                        'in_factory' => $param['factory_id'],
                        'stock_m_type' => $postdata['stock_m_type'],
                        'client_ordernum' => $postdata['res_id'],
                        'order_id' => 0,
                        'sku' =>'',
                        'cloth_num' => $param['cloth_num'],
                        'storehouse_id' => $param['storehouse_id'],
                        'storeshelf_id' => $param['storeshelf_id'],
                        'unit' => $param['unit'],
                        'remark' => $param['remark'],
                    ];
                    break;
            }
            $stockServer = new StockService();
            $changeStockList = $stockServer->applyCheckIn($changeStockList,'',false);
            $changeStockList = $changeStockList[0];
            //2,执行入库
            $new_stock = [];
            $new_stock[] = [
                'apply_id' => $changeStockList['actionid'],
                'stock' => $param['use_num'],
                'in_factory' => $param['factory_id'],
                'storehouse_id' => $param['storehouse_id'],
                'storeshelf_id' => $param['storeshelf_id'],
            ];
            $stockServer->doCheckIn($new_stock);
            return json(['code' => 1, 'msg' => '入库成功,即将关闭当前窗口', 'data' => [],]);
        }
        $info = db('material m')
            ->field('m.id,m.material_sku,m.type,m.unit
            ')
            ->where([
                ['m.material_sku', '=', $material_sku],
            ])
            ->find();
        $factoryKV = getFactoryKV(true);
        $unitKV = getUnitKV();
        $storehouseKV = getStorehouseKV();
        $storeshelfKV = getStoreshelfKV();
        $storeshelfMap = [];
        foreach ($storehouseKV as $k => $v) {
            if ($k > 0) $storeshelfMap[$k] = getStoreshelfKV($k);
        }
        $this->assign('info', $info);
        $this->assign('factoryKV', ['0' => '请选择'] + $factoryKV);
        $this->assign('storehouseKV', ['' => '请选择'] + $storehouseKV);
        $this->assign('storeshelfKV', ['' => '请选择'] + $storeshelfKV);
        $this->assign('storeshelfMap', $storeshelfMap);
        $this->assign('unitKV', $unitKV);
        return $this->fetch();
    }
}